<template>
  <div class="product-detail bg-gray-50 dark:bg-gray-900 min-h-screen">
    <!-- 面包屑导航 -->
    <div class="container mx-auto px-4 py-4">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/shop' }"
          >文创商城</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{ path: '/shop', query: { category: product.categoryId } }"
        >
          {{ product.categoryName }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>{{ product.title }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 店铺信息卡片 -->
    <div class="container mx-auto px-4 mb-4">
      <div
        class="bg-white dark:bg-gray-800 rounded-xl shadow-md border border-gray-100 dark:border-gray-700"
      >
        <div
          class="shop-info bg-gray-50/50 dark:bg-gray-700/30 rounded-lg p-6 relative group"
        >
          <div class="flex items-center justify-between">
            <div
              class="flex items-center gap-4 cursor-pointer group"
              @click="goToShop"
            >
              <div class="relative">
                <el-avatar
                  :size="48"
                  :src="store.avatar"
                  class="transition-transform group-hover:scale-105 shadow-sm"
                />
                <!-- 店铺标识 -->
                <div
                  class="absolute -top-2 left-1 bg-primary-500 text-white px-2 py-0.5 text-xs rounded-full shadow-sm"
                >
                  店铺
                </div>
              </div>
              <div>
                <div
                  class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-1 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors flex items-center gap-2"
                >
                  {{ store.name }}
                  <el-icon
                    class="text-sm opacity-0 group-hover:opacity-100 transition-opacity"
                    ><ArrowRight
                  /></el-icon>
                </div>
                <div
                  class="flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400"
                >
                  <span>商品 {{ store.productCount }}</span>
                  <span>关注 {{ store.followers }}</span>
                  <span>好评率 {{ store.positiveRate }}%</span>
                </div>
              </div>
            </div>
            <div class="flex items-center gap-3">
              <el-button
                type="primary"
                :plain="!store.isFollowed"
                @click.stop="followStore"
                :loading="followLoading"
                class="hover:shadow-md transition-shadow"
              >
                {{ store.isFollowed ? "已关注" : "+ 关注店铺" }}
              </el-button>
              <el-button
                type="primary"
                class="shop-enter-btn hover:shadow-md transition-shadow"
                @click="goToShop"
              >
                <el-icon class="mr-1"><Shop /></el-icon>
                进店逛逛
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4">
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm">
        <div class="flex flex-col lg:flex-row">
          <!-- 左侧图片区域 -->
          <div class="lg:w-[500px] flex-shrink-0">
            <!-- 主图预览 -->
            <div class="relative">
              <el-carousel
                trigger="click"
                height="500px"
                indicator-position="outside"
                :autoplay="false"
                class="product-carousel"
              >
                <el-carousel-item
                  v-for="(image, index) in product.images"
                  :key="index"
                >
                  <div
                    class="image-wrapper relative h-full"
                    @click="showImageViewer(index)"
                  >
                    <el-image
                      :src="image"
                      fit="contain"
                      class="w-full h-full cursor-zoom-in"
                      :preview-src-list="product.images"
                      :initial-index="index"
                    />
                  </div>
                </el-carousel-item>
              </el-carousel>

              <!-- 视频预览（如果有） -->
              <div v-if="product.video" class="absolute top-4 right-4">
                <el-button type="primary" circle @click="showVideo = true">
                  <el-icon><VideoPlay /></el-icon>
                </el-button>
              </div>
            </div>

            <!-- 缩略图列表 -->
            <div class="thumbnail-list flex gap-2 mt-4 px-4">
              <div
                v-for="(image, index) in product.images"
                :key="index"
                class="thumbnail-item w-20 h-20 rounded-lg border-2 cursor-pointer transition-all"
                :class="[
                  currentImageIndex === index
                    ? 'border-primary-500'
                    : 'border-transparent',
                ]"
                @click="currentImageIndex = index"
              >
                <el-image
                  :src="image"
                  fit="cover"
                  class="w-full h-full rounded-lg"
                />
              </div>
            </div>

            <!-- 分享区域 -->
            <div
              class="share-section flex items-center gap-4 mt-6 px-4 py-3 border-t dark:border-gray-700"
            >
              <span class="text-gray-500 dark:text-gray-400">分享</span>
              <div class="share-icons flex gap-3">
                <el-button circle>
                  <el-icon><Share /></el-icon>
                </el-button>
                <el-button circle>
                  <el-icon><ChatDotRound /></el-icon>
                </el-button>
                <el-button circle>
                  <el-icon><Link /></el-icon>
                </el-button>
              </div>
            </div>
          </div>

          <!-- 右侧信息区域 -->
          <div class="flex-1 p-6 lg:pl-8">
            <!-- 商品标题 -->
            <h1
              class="text-2xl font-bold text-gray-900 dark:text-gray-100 mb-4"
            >
              <span
                v-if="product.isNew || (product.tags && product.tags.includes('新品'))"
                class="bg-red-500 text-white text-sm px-2 py-0.5 rounded mr-2"
                >新品</span
              >
              {{ product.name || product.title }}
            </h1>

            <!-- 商品简介 -->
            <div class="text-gray-500 dark:text-gray-400 mb-6">
              {{ product.description || product.brief }}
            </div>

            <!-- 价格区域 -->
            <div
              class="price-section bg-gray-50 dark:bg-gray-700/50 p-4 rounded-lg mb-6"
            >
              <div class="flex items-baseline gap-4">
                <span class="text-3xl font-bold text-red-600 dark:text-red-400"
                  >¥{{ product.price }}</span
                >
                <span class="text-gray-400 dark:text-gray-500 line-through"
                  >¥{{ product.originalPrice }}</span
                >
                <span
                  v-if="product.discount"
                  class="bg-red-500 text-white px-2 py-0.5 rounded text-sm"
                >
                  {{ product.discount }}折
                </span>
              </div>

              <!-- 促销信息 -->
              <div class="mt-4 space-y-2" v-if="product.promotions?.length">
                <div
                  v-for="promo in product.promotions"
                  :key="promo.id"
                  class="flex items-center gap-2 text-sm"
                >
                  <span
                    class="bg-primary-500/10 text-primary-500 px-2 py-0.5 rounded"
                    >{{ promo.type }}</span
                  >
                  <span class="text-gray-600 dark:text-gray-300">{{
                    promo.description
                  }}</span>
                </div>
              </div>
            </div>

            <!-- 运费信息 -->
            <div
              class="delivery-info flex items-center gap-6 text-gray-600 dark:text-gray-300 mb-6"
            >
              <div class="flex items-center gap-2">
                <el-icon><Location /></el-icon>
                <span>配送至：</span>
                <el-cascader
                  v-model="selectedRegion"
                  :options="regionOptions"
                  placeholder="请选择地区"
                  size="small"
                />
              </div>
              <div>
                运费：<span class="text-gray-900 dark:text-gray-100"
                  >¥{{ deliveryFee || "免运费" }}</span
                >
              </div>
              <div>
                月销量：<span class="text-primary-500">{{
                  product.monthlySales
                }}</span>
              </div>
            </div>

            <!-- 服务承诺 -->
            <div
              class="service-promises flex items-center gap-6 text-sm text-gray-600 dark:text-gray-300 mb-6"
            >
              <div
                v-for="service in services"
                :key="service.text"
                class="flex items-center gap-1"
              >
                <el-icon><Check /></el-icon>
                <span>{{ service.text }}</span>
              </div>
            </div>

            <!-- 规格选择 -->
            <div class="specs-section space-y-4 mb-6">
              <div
                v-for="spec in product.specs"
                :key="spec.name"
                class="spec-item"
              >
                <div class="text-gray-600 dark:text-gray-300 mb-2">
                  {{ spec.name }}
                </div>
                <div class="flex flex-wrap gap-2">
                  <el-button
                    v-for="option in spec.options"
                    :key="option.id"
                    :type="
                      selectedSpecs[spec.name] === option.id
                        ? 'primary'
                        : 'default'
                    "
                    @click="selectSpec(spec.name, option.id)"
                    class="spec-button"
                  >
                    <template v-if="option.image">
                      <el-image
                        :src="option.image"
                        class="w-6 h-6 rounded mr-1"
                      />
                    </template>
                    {{ option.value }}
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 数量选择 -->
            <div class="quantity-section flex items-center gap-4 mb-8">
              <span class="text-gray-600 dark:text-gray-300">数量</span>
              <el-input-number
                v-model="quantity"
                :min="1"
                :max="product.stock"
                :step="1"
              />
              <span class="text-gray-500 dark:text-gray-400">
                库存 {{ product.stock }} 件
              </span>
            </div>

            <!-- 购买按钮组 -->
            <div class="purchase-actions flex gap-4">
              <el-button
                type="danger"
                size="large"
                class="flex-1"
                :loading="buyLoading"
                @click="buyNow"
              >
                立即购买
              </el-button>
              <el-button
                type="warning"
                size="large"
                class="flex-1"
                :loading="cartLoading"
                @click="addToCart"
              >
                加入购物车
              </el-button>
              <el-button
                :type="product.isFavorite ? 'primary' : 'default'"
                size="large"
                @click="toggleFavorite"
              >
                <el-icon><Star /></el-icon>
                <span class="ml-1">{{
                  product.isFavorite ? "已收藏" : "收藏"
                }}</span>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品详情区域 -->
      <div class="mt-8 bg-white dark:bg-gray-800 rounded-lg shadow-sm">
        <el-tabs v-model="activeTab" class="product-tabs">
          <el-tab-pane label="商品详情" name="detail">
            <div class="p-6">
              <!-- 商品参数 -->
              <div class="parameters-section mb-8">
                <h3
                  class="text-lg font-bold text-gray-900 dark:text-gray-100 mb-4"
                >
                  商品参数
                </h3>
                <el-descriptions :column="2" border>
                  <el-descriptions-item
                    v-for="param in product.parameters"
                    :key="param.key"
                    :label="param.key"
                  >
                    {{ param.value }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>

              <!-- 图文详情 -->
              <div class="detail-content">
                <h3
                  class="text-lg font-bold text-gray-900 dark:text-gray-100 mb-4"
                >
                  图文详情
                </h3>
                <div class="rich-text" v-html="product.description"></div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="商品评价" name="reviews">
            <product-reviews :product-id="product.id" />
          </el-tab-pane>

          <el-tab-pane label="购买须知" name="notice">
            <div class="p-6 space-y-6">
              <div v-for="(notice, index) in notices" :key="index">
                <h3
                  class="text-lg font-bold text-gray-900 dark:text-gray-100 mb-3"
                >
                  {{ notice.title }}
                </h3>
                <div class="text-gray-600 dark:text-gray-300">
                  {{ notice.content }}
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 相关商品推荐 -->
      <div class="mt-8 bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
        <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100 mb-6">
          相关商品推荐
        </h3>
        
        <div v-if="recommendedProducts.length" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div
            v-for="product in recommendedProducts"
            :key="product.id"
            class="recommended-product bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden hover:shadow-md transition-all duration-300 cursor-pointer"
            @click="$router.push(`/shop/product/${product.id}`)"
          >
            <!-- 商品图片 -->
            <div class="product-image-wrapper relative overflow-hidden">
              <el-image
                :src="product.image"
                fit="cover"
                class="w-full h-48 transition-transform duration-300 hover:scale-110"
              />
            </div>
            
            <!-- 商品信息 -->
            <div class="p-4">
              <h4 class="text-md font-medium text-gray-900 dark:text-white line-clamp-2 mb-2">
                {{ product.title || product.name }}
              </h4>
              
              <div class="flex items-start justify-between">
                <div>
                  <div class="text-lg font-bold text-primary-600 dark:text-primary-400">
                    ¥{{ formatPrice(product.price) }}
                  </div>
                  <div class="text-sm text-gray-500 dark:text-gray-400">
                    已售 {{ product.sales || 0 }}
                  </div>
                </div>
                
                <el-button
                  circle
                  type="primary"
                  size="small"
                  @click.stop="handleAddToCart(product)"
                >
                  <el-icon><ShoppingCart /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
        
        <el-empty v-else description="暂无相关商品推荐"></el-empty>
      </div>
    </div>

    <!-- 视频预览弹窗 -->
    <el-dialog
      v-model="showVideo"
      title="商品视频"
      width="800px"
      :close-on-click-modal="false"
    >
      <video :src="product.video" class="w-full" controls autoplay></video>
    </el-dialog>

    <!-- 右侧悬浮工具栏 -->
    <div class="fixed right-6 bottom-48 flex flex-col gap-4 items-end">
      <el-tooltip
        content="购物车"
        placement="left"
        effect="dark"
        class="toolbar-tooltip"
      >
        <el-button
          circle
          size="large"
          type="primary"
          class="w-16 h-16 flex items-center justify-center shadow-lg hover:scale-110 transition-transform"
          @click="showCart = true"
        >
          <el-badge
            v-if="cartItemCount"
            :value="cartItemCount"
            class="cart-badge"
          >
            <el-icon class="text-2xl"><ShoppingCart /></el-icon>
          </el-badge>
          <el-icon v-else class="text-2xl"><ShoppingCart /></el-icon>
        </el-button>
      </el-tooltip>

      <el-tooltip
        content="我的收藏"
        placement="left"
        effect="dark"
        class="toolbar-tooltip"
      >
        <el-button
          circle
          size="large"
          type="primary"
          class="w-16 h-16 flex items-center justify-center shadow-lg hover:scale-110 transition-transform"
          @click="showFavorites = true"
        >
          <el-badge
            v-if="favoriteCount"
            :value="favoriteCount"
            class="favorite-badge"
          >
            <el-icon class="text-2xl"><Star /></el-icon>
          </el-badge>
          <el-icon v-else class="text-2xl"><Star /></el-icon>
        </el-button>
      </el-tooltip>

      <el-tooltip
        content="联系客服"
        placement="left"
        effect="dark"
        class="toolbar-tooltip"
      >
        <el-button
          circle
          size="large"
          type="primary"
          class="w-16 h-16 flex items-center justify-center shadow-lg hover:scale-110 transition-transform"
          @click="showCustomerService"
        >
          <el-icon class="text-2xl"><Service /></el-icon>
        </el-button>
      </el-tooltip>
    </div>

    <!-- 客服组件 -->
    <merchant-service ref="merchantServiceRef" :product="product" />

    <!-- 购物车抽屉 -->
    <el-drawer
      v-model="showCart"
      title="购物车"
      size="400px"
      :with-header="false"
    >
      <div class="cart-drawer h-full flex flex-col">
        <div
          class="drawer-header flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700"
        >
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">
            购物车
          </h3>
          <el-button
            v-if="cartItems.length"
            type="danger"
            text
            :icon="Delete"
            @click="handleClearCart"
          >
            清空
          </el-button>
        </div>

        <!-- 购物车列表 -->
        <div
          v-if="cartItems.length"
          class="cart-items flex-1 overflow-y-auto p-4"
        >
          <div
            v-for="item in cartItems"
            :key="item.id"
            class="cart-item bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden mb-4 transition-all duration-300 hover:shadow-md"
          >
            <div class="flex p-4 gap-4">
              <div
                class="item-image w-24 h-24 rounded-lg overflow-hidden flex-shrink-0"
              >
                <el-image
                  :src="item.image"
                  :alt="item.title"
                  class="w-full h-full object-cover"
                  fit="cover"
                />
              </div>
              <div class="item-info flex-1 min-w-0">
                <div
                  class="item-name text-gray-900 dark:text-white font-medium mb-2 line-clamp-2 hover:text-primary-600 transition-colors"
                >
                  {{ item.title }}
                </div>
                <div class="item-price flex items-center justify-between">
                  <span
                    class="price text-primary-600 dark:text-primary-400 font-semibold"
                  >
                    ¥{{ formatPrice(item.price) }}
                  </span>
                  <el-input-number
                    v-model="item.quantity"
                    :min="1"
                    :max="item.stock || 99"
                    size="small"
                    @change="handleQuantityChange(item)"
                  />
                </div>
              </div>
              <el-button
                class="remove-button text-gray-400 hover:text-red-500 transition-colors"
                type="text"
                :icon="Close"
                @click="handleRemoveFromCart(item)"
              />
            </div>
          </div>
        </div>

        <!-- 空购物车状态 -->
        <el-empty v-else description="暂无购物商品">
          <el-button type="primary" @click="showCart = false">
            去逛逛
          </el-button>
        </el-empty>

        <!-- 购物车底部 -->
        <div
          v-if="cartItems.length"
          class="cart-footer bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 p-4"
        >
          <div class="total-price flex items-center justify-between mb-4">
            <span class="label text-gray-600 dark:text-gray-400">合计:</span>
            <span
              class="amount text-xl font-bold text-primary-600 dark:text-primary-400"
            >
              ¥{{ formatPrice(totalPrice) }}
            </span>
          </div>
          <el-button
            type="primary"
            class="checkout-button w-full h-12 text-lg font-medium"
            :loading="checkoutLoading"
            @click="handleCheckout"
          >
            结算 ({{ cartItemCount }}件)
          </el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 收藏夹抽屉 -->
    <el-drawer v-model="showFavorites" title="我的收藏" size="400px">
      <div class="favorites-drawer">
        <div v-if="favoriteItems.length" class="favorite-items">
          <div
            v-for="item in favoriteItems"
            :key="item.id"
            class="favorite-item"
          >
            <div class="item-image">
              <el-image :src="item.image" :alt="item.title" fit="cover" />
            </div>
            <div class="item-info">
              <div class="item-name">{{ item.title }}</div>
              <div class="item-price">¥{{ formatPrice(item.price) }}</div>
            </div>
            <div class="item-actions">
              <el-button
                type="primary"
                size="small"
                @click="handleAddToCart(item)"
              >
                加入购物车
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleRemoveFavorite(item)"
              >
                取消收藏
              </el-button>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无收藏商品">
          <el-button type="primary" @click="showFavorites = false">
            去逛逛
          </el-button>
        </el-empty>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  VideoPlay,
  Share,
  ChatDotRound,
  Link,
  Location,
  Check,
  Star,
  Service,
  ArrowRight,
  Shop,
  ShoppingCart,
  Delete,
  Close,
} from "@element-plus/icons-vue";
import ProductReviews from "@/components/shop/ProductReviews.vue";
import MerchantService from "@/components/shop/MerchantService.vue";
import service from "@/api/axios";
import { useUserStore } from "@/stores/user";

export default {
  name: "ProductDetail",
  components: {
    ProductReviews,
    MerchantService,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const userStore = useUserStore();
    
    // 获取商品ID
    const productId = route.params.id;

    // 基础数据
    const product = ref({
      id: productId,
      title: "贵港特色手工艺品 - 精美陶瓷茶具套装",
      brief:
        "传统手工制作，每一件都是独特的艺术品。套装包含茶壶、茶杯、茶盘等完整茶具。",
      price: 299,
      originalPrice: 399,
      discount: 7.5,
      categoryId: 1,
      categoryName: "手工艺品",
      tags: ["new"],
      images: [
        "https://img2.baidu.com/it/u=1159203698,2924032871&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
        "http://t13.baidu.com/it/u=2485201983,4177352003&fm=224&app=112&f=JPEG?w=500&h=500",
        "https://img2.baidu.com/it/u=486554850,24928460&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
        "https://img2.baidu.com/it/u=94659050,2912705704&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
      ],
      video:
        "https://vdept3.bdstatic.com/mda-ng5b82pmsd94di1v/cae_h264/1657096956317774043/mda-ng5b82pmsd94di1v.mp4?v_from_s=hkapp-haokan-hnb&auth_key=1741679005-0-0-034eff5a31aa1ca0aa638d69be297142&bcevod_channel=searchbox_feed&pd=1&cr=0&cd=0&pt=3&logid=2605822777&vid=6348888505666772127&klogid=2605822777&abtest=132219_1",
      stock: 999,
      monthlySales: 286,
      promotions: [
        { id: 1, type: "满减", description: "满500减50" },
        { id: 2, type: "活动", description: "新品首发，限时85折" },
      ],
      specs: [
        {
          name: "套装款式",
          options: [
            {
              id: 1,
              value: "经典款（8件套）",
              image: "/images/specs/classic.jpg",
            },
            {
              id: 2,
              value: "豪华款（12件套）",
              image: "/images/specs/deluxe.jpg",
            },
          ],
        },
        {
          name: "颜色",
          options: [
            { id: 1, value: "青瓷绿" },
            { id: 2, value: "天青色" },
            { id: 3, value: "玉白色" },
          ],
        },
      ],
      parameters: [
        { key: "材质", value: "景德镇瓷土" },
        { key: "产地", value: "广西贵港" },
        { key: "工艺", value: "手工制作" },
        { key: "适用场景", value: "茶室、会客厅、办公室" },
        { key: "保养说明", value: "中性清洁剂清洗，避免磕碰" },
      ],
      description: "<p>详细的图文描述...</p>",
      isFavorite: false,
    });

    // 店铺信息
    const store = ref({
      id: 1,
      name: "贵港特色手工艺品店",
      avatar: "https://img1.baidu.com/it/u=2428499488,117108639&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
      productCount: 100,
      followers: 500,
      positiveRate: 95,
      isFollowed: false,
    });

    // 检查用户是否已登录
    const checkLogin = () => {
      if (!userStore.isLoggedIn) {
        ElMessageBox.confirm(
          '此功能需要登录后使用，是否立即登录？',
          '提示',
          {
            confirmButtonText: '去登录',
            cancelButtonText: '取消',
            type: 'info'
          }
        ).then(() => {
          // 保存当前页面路径，登录后返回
          localStorage.setItem('redirectPath', router.currentRoute.value.fullPath);
          router.push('/login');
        }).catch(() => {
          // 用户取消登录
        });
        return false;
      }
      return true;
    };

    // 服务承诺
    const services = [
      { text: "正品保证" },
      { text: "7天无理由退换" },
      { text: "48小时发货" },
      { text: "免费包邮" },
    ];

    // 购买须知
    const notices = [
      {
        title: "发货说明",
        content: "商品将在付款后48小时内发出，节假日除外。",
      },
      {
        title: "退换政策",
        content: "本商品支持7天无理由退换，请保持商品完好。",
      },
      {
        title: "保养说明",
        content: "请使用中性清洁剂清洗，避免磕碰，以延长使用寿命。",
      },
    ];

    // 状态管理
    const currentImageIndex = ref(0);
    const showVideo = ref(false);
    const activeTab = ref("detail");
    const selectedRegion = ref([]);
    const selectedSpecs = reactive({});
    const quantity = ref(1);
    const buyLoading = ref(false);
    const cartLoading = ref(false);
    const merchantServiceRef = ref(null);
    const followLoading = ref(false);
    const deliveryFee = ref(0);

    // 地区选择器数据
    const regionOptions = [
      {
        value: "guangxi",
        label: "广西",
        children: [
          {
            value: "guigang",
            label: "贵港",
            children: [
              { value: "gangbei", label: "港北区" },
              { value: "gangnan", label: "港南区" },
            ],
          },
        ],
      },
    ];

    // 获取商品详情数据
    const fetchProductDetail = async () => {
      try {
        console.log('正在获取商品详情，ID:', productId);
        const response = await service.get(`/public/shop/products/${productId}`);
        if (response && response.data) {
          // 合并API返回的数据，保留测试数据中可能不存在的字段
          const apiProduct = response.data;
          
          console.log('API返回的数据:', apiProduct);
          
          // 完全替换整个产品对象，避免部分数据未更新的问题
          product.value = {
            ...product.value, // 保留默认值作为备份
            ...apiProduct,    // 覆盖API返回的所有值
            // 确保关键字段名称匹配
            title: apiProduct.name || apiProduct.title || product.value.title,
            brief: apiProduct.description || apiProduct.brief || product.value.brief,
          };
          
          // 特别确保图片数组被正确更新
          if (apiProduct.images && apiProduct.images.length > 0) {
            product.value.images = [...apiProduct.images];
            console.log('更新后的产品图片:', product.value.images);
          }
          
          // 计算折扣率（如果没有）
          if (!product.value.discount && product.value.originalPrice && product.value.price) {
            product.value.discount = Math.round((product.value.price / product.value.originalPrice) * 10);
            console.log('计算折扣率:', product.value.discount);
          }
          
          // 处理规格数据 - 修复处理逻辑
          if (apiProduct.specGroups && apiProduct.specGroups.length > 0) {
            console.log('原始规格组数据:', apiProduct.specGroups);
            
            try {
              // 转换规格数据为前端需要的格式
              product.value.specs = apiProduct.specGroups.map(group => {
                // 检查group对象结构
                console.log('处理规格组:', group);
                
                return {
                  name: group.name,
                  options: Array.isArray(group.specs) ? group.specs.map((spec, index) => ({
                    id: spec.id || index + 1,
                    value: spec.specValue || spec.value || '',
                    image: spec.specImage || spec.image || ''
                  })) : []
                };
              });
              
              console.log('转换后的规格数据:', product.value.specs);
            } catch (err) {
              console.error('规格数据处理错误:', err);
              
              // 备用转换方案 - 如果上面的转换失败，尝试另一种结构
              product.value.specs = [];
              for (const group of apiProduct.specGroups) {
                if (group && group.name) {
                  const specOptions = [];
                  
                  // 尝试从不同可能的属性获取规格选项
                  const specsList = group.specs || group.values || group.options || [];
                  if (Array.isArray(specsList) && specsList.length > 0) {
                    specsList.forEach((spec, index) => {
                      specOptions.push({
                        id: spec.id || index + 1,
                        value: spec.specValue || spec.value || spec.name || '',
                        image: spec.specImage || spec.image || ''
                      });
                    });
                  }
                  
                  product.value.specs.push({
                    name: group.name,
                    options: specOptions
                  });
                }
              }
              console.log('备用方案转换后的规格数据:', product.value.specs);
            }
          } else {
            console.log('API未返回规格组数据或为空数组');
          }
          
          // 检查API是否返回店铺信息，如果有则获取店铺信息
          if (apiProduct.merchantId) {
            console.log('获取商家信息，ID:', apiProduct.merchantId);
            fetchStoreInfo(apiProduct.merchantId);
          }
          
          // 获取是否已收藏
          if (userStore.isLoggedIn) {
            checkIsFavorite();
          }
          
          console.log('处理后的商品数据:', product.value);
        }
      } catch (error) {
        console.error("获取商品详情失败:", error);
        ElMessage.error("获取商品详情失败，请稍后重试");
        // 保留默认测试数据
      }
    };

    // 获取店铺信息
    const fetchStoreInfo = async (storeId) => {
      try {
        const response = await service.get(`/public/shop/stores/${storeId}`);
        if (response && response.data) {
          console.log('获取到店铺信息:', response.data);
          
          // 更新店铺信息，直接替换整个对象
          store.value = {
            ...store.value, // 保留默认值
            ...response.data // 覆盖API返回的所有值
          };
          
          // 确保店铺名称正确设置
          if (response.data.name) {
            store.value.name = response.data.name;
          }
          
          // 确保店铺头像有效，如果API返回的为空或指向本地资源，使用默认头像
          if (!store.value.avatar || store.value.avatar.startsWith('/images/')) {
            store.value.avatar = "https://img1.baidu.com/it/u=2428499488,117108639&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500";
          }
          
          console.log('更新后的店铺信息:', store.value);
        }
      } catch (error) {
        console.error("获取店铺信息失败:", error);
        // 错误时确保店铺头像有效
        if (store.value.avatar && store.value.avatar.startsWith('/images/')) {
          store.value.avatar = "https://img1.baidu.com/it/u=2428499488,117108639&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500";
        }
      }
    };

    // 检查商品是否已收藏
    const checkIsFavorite = async () => {
      if (!userStore.isLoggedIn) return;
      
      try {
        const response = await service.get(`/shop/favorites/check/${productId}`);
        if (response !== undefined) {
          // 只更新收藏状态，其他属性保持不变
          product.value.isFavorite = response;
        }
      } catch (error) {
        console.error("检查收藏状态失败:", error);
        // 这里不显示错误提示，因为未登录用户访问时会触发此错误
        // 保留默认状态
      }
    };

    // 关注店铺
    const followStore = async () => {
      if (!checkLogin()) return;
      
      followLoading.value = true;
      try {
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 300));
        
        // 直接修改前端状态，不调用API
        if (store.value.isFollowed) {
          ElMessage.success("已取消关注");
          // 如果取消关注，粉丝数减1
          store.value.followers--;
        } else {
          ElMessage.success("关注成功");
          // 如果关注，粉丝数加1
          store.value.followers++;
        }
        
        // 更新关注状态
        store.value.isFollowed = !store.value.isFollowed;
      } catch (error) {
        console.error("关注店铺操作模拟失败:", error);
        ElMessage.error("操作失败，请重试");
      } finally {
        followLoading.value = false;
      }
    };

    // 跳转到店铺页面
    const goToShop = () => {
      router.push(`/shop/store/${store.value.id}`);
    };

    // 选择规格
    const selectSpec = (specName, optionId) => {
      selectedSpecs[specName] = optionId;
    };

    // 检查是否已选择所有规格
    const checkSpecsSelected = () => {
      const requiredSpecs = product.value.specs.map((spec) => spec.name);
      const selectedSpecsKeys = Object.keys(selectedSpecs);
      return requiredSpecs.every((spec) => selectedSpecsKeys.includes(spec));
    };

    // 立即购买
    const buyNow = async () => {
      if (!checkLogin()) return;
      
      if (product.value.specs && product.value.specs.length > 0 && !checkSpecsSelected()) {
        ElMessage.warning("请选择商品规格");
        return;
      }

      buyLoading.value = true;
      try {
        // 构建订单数据
        const orderData = {
          productId: product.value.id,
          title: product.value.title || product.value.name,
          image: product.value.images[0],
          price: product.value.price,
          specs: selectedSpecs,
          quantity: quantity.value,
          description: product.value.brief || product.value.description,
          merchantId: store.value.id,
          merchantName: store.value.name,
        };

        router.push({
          path: "/order/confirm",
          query: {
            type: "product",
            data: encodeURIComponent(JSON.stringify(orderData)),
          },
        });
      } catch (error) {
        console.error("跳转购买页面失败:", error);
        ElMessage.error("操作失败，请重试");
      } finally {
        buyLoading.value = false;
      }
    };

    // 加入购物车
    const addToCart = async () => {
      if (!checkLogin()) return;
      
      if (product.value.specs && product.value.specs.length > 0 && !checkSpecsSelected()) {
        ElMessage.warning("请选择商品规格");
        return;
      }

      cartLoading.value = true;
      try {
        const cartItem = {
          productId: product.value.id,
          quantity: quantity.value,
          selected: true,
          specs: selectedSpecs
        };
        
        await service.post("/shop/cart/add", cartItem);
        ElMessage.success("已添加到购物车");
        // 刷新购物车列表
        fetchCartItems();
      } catch (error) {
        console.error("添加到购物车失败:", error);
        ElMessage.error("添加失败，请重试");
      } finally {
        cartLoading.value = false;
      }
    };

    // 收藏商品
    const toggleFavorite = async () => {
      if (!checkLogin()) return;
      
      try {
        if (product.value.isFavorite) {
          // 取消收藏
          await service.delete(`/shop/favorites/${product.value.id}`);
          ElMessage.success("已取消收藏");
        } else {
          // 添加收藏
          await service.post(`/shop/favorites/add`, { productId: product.value.id });
          ElMessage.success("收藏成功");
        }
        
        // 更新收藏状态
        product.value.isFavorite = !product.value.isFavorite;
        
        // 如果收藏夹已打开，刷新列表
        if (showFavorites.value) {
          fetchFavoriteList();
        }
      } catch (error) {
        console.error("操作收藏失败:", error);
        ElMessage.error("操作失败，请重试");
      }
    };

    // 显示客服
    const showCustomerService = () => {
      merchantServiceRef.value?.open();
    };

    // 返回顶部
    const scrollToTop = () => {
      window.scrollTo({ top: 0, behavior: "smooth" });
    };

    // 价格格式化
    const formatPrice = (price) => {
      return parseFloat(price).toFixed(2);
    };

    // 购物车相关
    const showCart = ref(false);
    const cartItems = ref([]);
    const checkoutLoading = ref(false);

    // 计算购物车商品数量
    const cartItemCount = computed(() => {
      return cartItems.value.reduce((total, item) => total + item.quantity, 0);
    });

    // 计算购物车总价
    const totalPrice = computed(() => {
      return cartItems.value.reduce((total, item) => {
        return total + item.price * item.quantity;
      }, 0);
    });

    // 获取购物车列表
    const fetchCartItems = async () => {
      if (!userStore.isLoggedIn) return;
      
      try {
        const response = await service.get("/shop/cart/list");
        if (response && response.data) {
          cartItems.value = response.data;
        }
      } catch (error) {
        console.error("获取购物车列表失败:", error);
        // 未登录时不显示错误消息
        // 保留默认空数组
      }
    };

    // 处理从购物车移除
    const handleRemoveFromCart = async (item) => {
      try {
        await service.delete(`/shop/cart/${item.id}`);
        // 更新列表
        const index = cartItems.value.findIndex((i) => i.id === item.id);
        if (index > -1) {
          cartItems.value.splice(index, 1);
        }
        ElMessage.success("已从购物车移除");
      } catch (error) {
        console.error("从购物车移除失败:", error);
        ElMessage.error("操作失败，请重试");
      }
    };

    // 处理清空购物车
    const handleClearCart = async () => {
      try {
        await ElMessageBox.confirm("确定要清空购物车吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        
        await service.delete("/shop/cart/clear");
        cartItems.value = [];
        ElMessage.success("购物车已清空");
      } catch (error) {
        if (error === 'cancel') {
          // 用户取消操作
          return;
        }
        console.error("清空购物车失败:", error);
        ElMessage.error("清空购物车失败");
      }
    };

    // 处理数量变化
    const handleQuantityChange = async (item) => {
      // 确保数量在有效范围内
      if (item.quantity < 1) {
        item.quantity = 1;
      }
      if (item.stock && item.quantity > item.stock) {
        item.quantity = item.stock;
        ElMessage.warning(`该商品库存只有 ${item.stock} 件`);
      }
      
      try {
        await service.put(`/shop/cart/update`, {
          id: item.id,
          quantity: item.quantity
        });
      } catch (error) {
        console.error("更新购物车数量失败:", error);
        ElMessage.error("更新数量失败");
        // 回滚数量变更
        fetchCartItems();
      }
    };

    // 处理结算
    const handleCheckout = async () => {
      if (!cartItems.value.length) {
        ElMessage.warning("购物车是空的");
        return;
      }

      checkoutLoading.value = true;
      try {
        // 获取已选中的商品ID
        const selectedItems = cartItems.value.filter(item => item.selected);
        if (selectedItems.length === 0) {
          ElMessage.warning("请选择要结算的商品");
          checkoutLoading.value = false;
          return;
        }
        
        // 跳转到结算页
        router.push({
          path: "/order/confirm",
          query: {
            type: "cart",
            items: selectedItems.map(item => item.id).join(",")
          }
        });
      } catch (error) {
        console.error("结算失败:", error);
        ElMessage.error("结算失败，请重试");
      } finally {
        checkoutLoading.value = false;
      }
    };

    // 收藏相关
    const showFavorites = ref(false);
    const favoriteItems = ref([]);
    const favoriteCount = computed(() => favoriteItems.value.length);

    // 获取收藏列表
    const fetchFavoriteList = async () => {
      if (!userStore.isLoggedIn) return;
      
      try {
        const response = await service.get("/shop/favorites/list");
        if (response && response.data) {
          favoriteItems.value = response.data;
        }
      } catch (error) {
        console.error("获取收藏列表失败:", error);
        // 未登录时不显示错误消息
        // 保留默认空数组
      }
    };

    // 处理取消收藏
    const handleRemoveFavorite = async (item) => {
      try {
        await service.delete(`/shop/favorites/${item.id}`);
        
        // 从列表中移除
        const index = favoriteItems.value.findIndex((i) => i.id === item.id);
        if (index > -1) {
          favoriteItems.value.splice(index, 1);
        }
        
        // 如果当前商品是被取消收藏的商品，更新状态
        if (item.id === product.value.id) {
          product.value.isFavorite = false;
        }
        
        ElMessage.success("已取消收藏");
      } catch (error) {
        console.error("取消收藏失败:", error);
        ElMessage.error("取消收藏失败");
      }
    };
    
    // 从收藏添加到购物车
    const handleAddToCart = async (item) => {
      try {
        await service.post("/shop/cart/add", {
          productId: item.id,
          quantity: 1,
          selected: true
        });
        
        ElMessage.success("已添加到购物车");
        // 刷新购物车
        fetchCartItems();
      } catch (error) {
        console.error("添加到购物车失败:", error);
        ElMessage.error("添加失败，请重试");
      }
    };

    // 监听抽屉显示状态
    watch(showFavorites, (val) => {
      if (val && userStore.isLoggedIn) {
        fetchFavoriteList();
      }
    });
    
    watch(showCart, (val) => {
      if (val && userStore.isLoggedIn) {
        fetchCartItems();
      }
    });

    // 添加推荐商品的获取函数
    const recommendedProducts = ref([]);
    
    const fetchRecommendedProducts = async () => {
      try {
        const response = await service.get('/public/shop/products/recommendations', {
          params: {
            productId: productId,  // 添加必要的参数
            limit: 10
          }
        });
        if (response && response.data) {
          recommendedProducts.value = response.data;
        }
      } catch (error) {
        console.error("获取推荐商品失败:", error);
        // 失败时使用默认推荐数据 - 如果需要可以在这里设置默认推荐数据
        recommendedProducts.value = [
          {
            id: 2,
            title: "贵港特色陶瓷茶具套装",
            price: 299,
            image: "https://img1.baidu.com/it/u=694461414,142604752&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=882",
            sales: 156
          },
          {
            id: 3,
            title: "贵港特色绣品装饰画",
            price: 459,
            image: "https://t15.baidu.com/it/u=1009955054,2854934985&fm=224&app=112&f=JPEG?w=292&h=500",
            sales: 89
          }
        ];
      }
    };

    onMounted(() => {
      // 获取商品详情数据
      fetchProductDetail();
      // 获取购物车数据
      if (userStore.isLoggedIn) {
        fetchCartItems();
      }
      // 获取推荐商品
      fetchRecommendedProducts();
    });

    return {
      product,
      services,
      notices,
      currentImageIndex,
      showVideo,
      activeTab,
      selectedRegion,
      regionOptions,
      selectedSpecs,
      quantity,
      buyLoading,
      cartLoading,
      selectSpec,
      buyNow,
      addToCart,
      toggleFavorite,
      showCustomerService,
      scrollToTop,
      merchantServiceRef,
      followStore,
      goToShop,
      followLoading,
      store,
      showCart,
      cartItems,
      checkoutLoading,
      cartItemCount,
      totalPrice,
      showFavorites,
      favoriteItems,
      favoriteCount,
      handleRemoveFromCart,
      handleClearCart,
      handleQuantityChange,
      handleCheckout,
      handleRemoveFavorite,
      handleAddToCart,
      formatPrice,
      deliveryFee,
      recommendedProducts,
      Delete,
      Close,
    };
  },
};
</script>

<style lang="scss" scoped>
.product-carousel {
  :deep(.el-carousel__indicators) {
    transform: translateY(1rem);
  }

  :deep(.el-carousel__button) {
    width: 30px;
    border-radius: 3px;
  }
}

.thumbnail-item {
  &:hover {
    transform: translateY(-2px);
  }
}

.product-tabs {
  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0 1rem;
    background-color: #f9fafb;
    @apply dark:bg-gray-700/50;
  }

  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
    @apply dark:bg-gray-700;
  }

  :deep(.el-tabs__item) {
    font-size: 1rem;
    height: 50px;
    line-height: 50px;
    @apply dark:text-gray-300;

    &.is-active {
      @apply dark:text-primary-400;
    }
  }
}

.rich-text {
  @apply max-w-full overflow-x-hidden;

  :deep(img) {
    @apply max-w-full h-auto;
  }

  :deep(p) {
    @apply mb-4;
  }
}

.spec-button {
  min-width: 80px;
}

// 购物车样式
.cart-drawer {
  .cart-item {
    .item-image {
      img {
        @apply transition-transform duration-300;
      }

      &:hover img {
        @apply scale-110;
      }
    }

    .item-name {
      &:hover {
        @apply cursor-pointer;
      }
    }

    .el-input-number {
      @apply w-24;
    }
  }

  .empty-cart {
    .el-icon {
      @apply opacity-50;
    }
  }

  .cart-footer {
    .checkout-button {
      @apply rounded-lg;
    }
  }
}

// 收藏夹样式
.favorites-drawer {
  .favorite-items {
    @apply space-y-4 p-4;

    .favorite-item {
      @apply flex items-start gap-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700;

      .item-image {
        @apply w-24 h-24 rounded-lg overflow-hidden flex-shrink-0;

        :deep(.el-image) {
          @apply w-full h-full object-cover;
        }
      }

      .item-info {
        @apply flex-1 min-w-0;

        .item-name {
          @apply font-medium text-gray-900 dark:text-white mb-2 line-clamp-2;
        }

        .item-price {
          @apply text-lg font-bold text-primary-600 dark:text-primary-400;
        }
      }

      .item-actions {
        @apply flex flex-col gap-2;
      }
    }
  }
}

// 自定义工具栏 tooltip 动画
:deep(.toolbar-tooltip) {
  .el-popper {
    transition:
      opacity 0.15s,
      transform 0.15s !important;
  }

  &.is-hidden {
    opacity: 0;
    transform: scaleY(0.9);
    transition:
      opacity 0.1s,
      transform 0.1s !important;
  }
}
</style>
